<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="400" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" ref="dialogForm" label-width="100px" label-position="left">
			<el-form-item label="所属字典"  >
        <el-input v-model="form.dictName" disabled ></el-input>
      </el-form-item>
			<el-form-item label="项名称" prop="dataCode">
				<el-input v-model="form.dataCode" clearable></el-input>
			</el-form-item>
			<el-form-item label="键值" prop="dataValue">
				<el-input v-model="form.dataValue" clearable></el-input>
			</el-form-item>
      <el-form-item label="排序号" prop="sortNum">
        <el-input-number v-model="form.sortNum" clearable></el-input-number>
      </el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import http from "@/utils/request.js";
import {ElMessage} from "element-plus";

// 定义props和emits
const props = defineProps({
	params: {
		type: Object,
		default: null
	}
})

const emit = defineEmits(['success', 'closed'])

// 响应式数据
const mode = ref("create")
const titleMap = reactive({
	add: '新增项',
	edit: '编辑项'
})
const visible = ref(false)
const isSaveing = ref(false)
const form = reactive({
	id: "",
	dataValue: "",
	dataCode: "",
	dict: "",
	dictName: "",
	sortNum: ""
})
const rules = reactive({
	dic: [
		{required: true, message: '请选择所属字典'}
	],
	dataCode: [
		{required: true, message: '请输入项名称'}
	],
	dataValue: [
		{required: true, message: '请输入键值'}
	]
})

// 模板引用
const dialogForm = ref(null)

// 方法
const open = (dict) => {
	form.dict = dict
	visible.value = true
	http.post(`/dict/view`, {id: dict}).then(res => {
    form.dictName = res.data.title
  })
	return this
}

const getDic = async () => {
	//var res = await this.$API.system.dic.tree.get();
	//this.dic = res.data;
}

const submit = () => {
	dialogForm.value.validate(async (valid) => {
		if (valid) {
			isSaveing.value = true
			let res = await http.post(`/dictItem/${mode.value}`, form)
			isSaveing.value = false
			if(res.code === 200){
				emit('success', form, mode.value)
				visible.value = false
        ElMessage.success("操作成功")
			}else{
        ElMessage.error(res.msg, "提示", {type: 'error'})
			}
		}
	})
}

const setData = (data) => {
  console.log("编辑")
	mode.value = "update"
	form.id = data.id
	form.dataCode = data.dataCode
	form.dataValue = data.dataValue
	form.sortNum = data.sortNum
}

// 生命周期
onMounted(() => {
	if(props.params){
		form.dic = props.params.code
	}
	getDic()
})

// 暴露方法给父组件使用
defineExpose({
	open,
	setData
})
</script>

<style>
</style>
